import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

/// 网络请求数据
/// 1. 添加http包
/// 2. 使用http包执行网络请求
/// 3. 转换响应的数据为Dart对象
/// 4. 加载和展示数据

class FetchDataApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final String appTitle = 'Fetch Data Demo';
    return MaterialApp(
      title: appTitle,
      theme: ThemeData(primarySwatch: Colors.red),
      home: FetchDataAppPage(title: appTitle),
    );
  }
}

class FetchDataAppPage extends StatefulWidget {
  final String title;

  FetchDataAppPage({Key key, this.title}) : super(key: key);

  @override
  State<StatefulWidget> createState() => FetchDataAppPageState();
}

class FetchDataAppPageState extends State<FetchDataAppPage> {
  Future<Post> post;

  @override
  void initState() {
    super.initState();
    post = fetchPost();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder<Post>(
          future: post,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data.title);
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            }
            return CircularProgressIndicator();
          }),
    );
  }
}

Future<Post> fetchPost() async {
  final response = await http.get(
    'https://jsonplaceholder.typicode.com/posts/1',
    // 请求头
    // headers: {HttpHeaders.authorizationHeader: "Basic your_api_token_here"}
  );
  if (response.statusCode == 200) {
    return Post.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load post.');
  }
}

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        userId: json['userId'],
        id: json['id'],
        title: json['title'],
        body: json['body']);
  }
}
